<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-row>
          <a-col :span="24">
            <a-result :status="statusType" :title="titleContent">
              <template #extra>
                <a-button key="console" type="primary" v-if="formData.type =='1'" @click="submitForm">上班打卡</a-button>
                <a-button key="buy" v-if="formData.type =='2'" @click="submitForm">下班打卡</a-button>
              </template>
            </a-result>
          </a-col>
        </a-row>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../TbSignRecord.api';
  import { queryOne } from '../TbSignRule.api';
  import { Form } from 'ant-design-vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import { SmileTwoTone } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import dayjs from 'dayjs';
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const formRef = ref();
  const signRule = ref();
  const useForm = Form.useForm;
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    userName: '',   
    signTime: '',   
    type: '',   
    status: '',   
  });
  const userStore = useUserStore();
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
  const statusType = ref<string>("info");
  const titleContent = ref<string>("请及时打卡");

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });

  
  /**
   * 新增
   */
  function add() {
    queryOne().then((responseResult: any) =>{
      signRule.value = responseResult;
      const currDate = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
      const currTime = convertToMinutes(dayjs(currDate).format('HH:mm'));
      const earlyDepartureTime = convertToMinutes(signRule.value.earlyDepartureTime);
      //const offdutyTime = convertToMinutes(signRule.value.offdutyTime);
      console.log(currTime+"====signRule.value====="+earlyDepartureTime);
      /* 如果当前时间小于早退时间就显示上班卡，否则就显示下班卡*/
      if(currTime < earlyDepartureTime){
        formData.type = "1";
      }else{
        formData.type = "2";
      }
      formData.signTime = currDate;
      formData.userName = userStore.getUserInfo.username;
    });
    edit({});
  }
  
  function convertToMinutes(timeString: string) {
    const [hours, minutes] = timeString.split(':').map(Number);
    return hours * 60 + minutes;
  }

  /**
   * 编辑
   */
  function edit(record) {
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });
  }
  
  function determineSignStatus(){
    console.log("======formData========"+JSON.stringify(formData))
    if(formData.type == "1"){
      const currTime = convertToMinutes(dayjs(formData.signTime).format('HH:mm'));
      const workingLateTime = convertToMinutes(signRule.value.workingLateTime);
      const workingAbsenteeismTime = convertToMinutes(signRule.value.workingAbsenteeismTime);
      
      if (currTime < workingLateTime) {
          formData.status = "2";
      }else if(currTime >= workingAbsenteeismTime) {
          formData.status = "4";
      }else {
          formData.status = "3";
      }
    }else if(formData.type == "2"){
      const currTime = convertToMinutes(dayjs(formData.signTime).format('HH:mm'));
      const offdutyTime = convertToMinutes(signRule.value.offdutyTime);
      const earlyDepartureTime = convertToMinutes(signRule.value.earlyDepartureTime);
      if (offdutyTime <= currTime) {
          formData.status = "2";
      }else {
          /*如果签到时间小于早退时间就是早退
          * 如果签到时间大于早退时间就是正常*/
          if (currTime>=earlyDepartureTime) {
              formData.status = "2";
          }else {
              formData.status = "5";
          }
      }
    }
  }

  /**
   * 提交数据
   */
  async function submitForm() {
    /* 校验是否迟到，正常打卡*/
    if(signRule.value.dropOutMan.indexOf(formData.userName) !== -1){
      createMessage.warning("您不参与打卡，无需打卡!");
      return;
    }else{
      determineSignStatus()
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;
    if (model.id) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          statusType.value = "success";
          titleContent.value = "您已经完成打卡!";
          //emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
